package de.koller.reason.gui.textureObj;

import de.koller.oceanFramework.OceanException;
import de.koller.oceanFramework.gl.util.ParticleTexture;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import javax.imageio.ImageIO;
import org.lwjgl.opengl.GL11;

public class TextureObject {
	
	private final ParticleTexture texture;
	private final float pixelScale;
	
	TextureObject( ParticleTexture texture ) {
		this.texture = texture;
		this.pixelScale = 1f / texture.getWidth();
	}
	
	public static TextureObject create( ParticleTexture texture ) {
		return new TextureObject( texture );
	}
	
	public static TextureObject create( String file ) {
		ClassLoader cl = TextureObject.class.getClassLoader();
		BufferedImage bi = null;
		
		try {
			InputStream in = cl.getResourceAsStream( file );
			bi = ImageIO.read( in );
		} catch( Exception ex ) {
			throw new OceanException( ex );
		}
		
		if( bi.getWidth() != bi.getHeight() )
			throw new IllegalArgumentException( "File have to be Texturevalid!" );
		
		ParticleTexture t = ParticleTexture.generate( bi.getWidth(), bi.getHeight() );
		for( int x = 0; x < bi.getWidth(); x++ )
			for( int y = 0; y < bi.getHeight(); y++ )
				t.setPixel( bi.getRGB( x, y ), x, y );
		t.flush();
		return new TextureObject( t );
	}
	
	public void bind() {
		texture.bind();
	}
	
	public void draw( float x, float y, float w, float h, float z, IPart part ) {
		float umin = pixelScale * part.getSubX();
		float umax = umin + pixelScale * part.getSubWidth();
		float vmin = pixelScale * part.getSubY();
		float vmax = vmin + pixelScale * part.getSubHeight();
		
		GL11.glBegin( GL11.GL_QUADS );
			GL11.glTexCoord2f( umin, vmin );
			GL11.glVertex3f( x, y, z );
			
			GL11.glTexCoord2f( umin, vmax );
			GL11.glVertex3f( x, y+h, z );
			
			GL11.glTexCoord2f( umax, vmax );
			GL11.glVertex3f( x+w, y+h, z );
			
			GL11.glTexCoord2f( umax, vmin );
			GL11.glVertex3f( x+w, y, z );
		GL11.glEnd();	
	}
	
	public void draw( float x, float y, float z, IPart part ) {
		this.draw( x, y, part.getSubWidth(), part.getSubHeight(), z, part );
	}
	
}
